import getLastEvent from "../utils/getLastEvent"
import getSelector from '../utils/getSelector'
import tracker from "../utils/tracker"

export function injectJsError(){
    // 监听全局未捕获的错误
    window.addEventListener('error', e => {
        console.log(e)
        let lastEvent = getLastEvent()
        const log = {
            kind: 'stability', // 监控指标的大类
            type: 'error', // 小类型
            errorType: 'jsError',
            url: e.filename, // 访问路径
            message: e.message, // 报错信息
            position: `${e.lineno}:${e.colno}`,
            stack: getLines(e.error.stack),
            selector: getSelector(lastEvent?.composedPath() || '')
        }
        tracker.send(log)
    })
}

function getLines(stack){
    return stack.split('\n').slice(1).map(item => item.replace(/^\s+at+\s+/, "")).join('^')
}